package Meter::Action::ChangePassword;

#===============================================================================
#     REVISION:  $Id: ChangePassword.pm 87 2011-07-18 10:18:01Z xdr.box@gmail.com $
#  DESCRIPTION:  Change user's password
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 87 $) [1];

use English qw( -no_match_vars );

#use Smart::Comments;

use Meter::Log;

use base qw(Meter::Action);

sub generate_page_content {
    my $self = shift;

    my $logger = get_logger();

    if ( $ENV{'REQUEST_METHOD'} eq 'GET' ) {
        return $self->process_template( 'change_password.tt2', {} );
    }

    my $username = $self->{'user'}->username();

    my $password       = $self->{'params'}{'password'};
    my $password_again = $self->{'params'}{'password_again'};

    if ( $password ne $password_again ) {
        $logger->warn("Password mismatch for user '$username'");

        return $self->redirect_error(
            'Ошибка смены пароля: пароли не совпадают',
            'change_password'
        );
    }

    eval {
        $self->{'user'}->password($password);
        $self->{'user'}->update();
    };

    if ($EVAL_ERROR) {
        my $why = $EVAL_ERROR;
        $logger->error("Cannot change password of user $username: $why");

        return $self->redirect_error( 'Ошибка смены пароля',
            'change_password', $why );
    }

    $logger->info(
        "Password of user '$username' has been successfully changed");

    return $self->redirect_ok( 'Пароль успешно изменён',
        'welcome' );
}

sub get_error_regexes_list {
    my $self = shift;

    return [
        {   regex => qr/\Qpassword fails 'regexp' constraint\E/xms,
            message =>
                'пароль не соответствует установленному формату',
        },
    ];
}

1;
